package fr.gunduz.springdatamongodb.facades.impl;

import fr.gunduz.springdatamongodb.facades.IBookFacade;
import fr.gunduz.springdatamongodb.model.Book;
import fr.gunduz.springdatamongodb.repositories.BookRepository;
import java.util.List;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

/**
 *
 * @author beytu
 */
@Service
public class BookFacade implements IBookFacade
{
	@Autowired private BookRepository bookRepository;
	@Autowired private MongoTemplate mongoTemplate;

	public Book add(Book book)
	{
		Assert.notNull(book,"Given book should not be null");
		Assert.isNull(book.getId(),"The object already have an ID. Use save mathod");
		
		book.setId(new ObjectId());
		
		return bookRepository.save(book);
	}
	
	public Book save(Book book)
	{
		Assert.notNull(book);
		Assert.notNull(book.getId(),"The object has no ID, cannot save it");
		return bookRepository.save(book);
	}

	public void delete(Book book)
	{
		Assert.notNull(book);
		Assert.notNull(book.getId(),"The object has no ID, cannot delete desired book");
		bookRepository.delete(book);
	}

	public List<Book> search(String title)
	{
		Assert.hasText(title,"You must provide a valid title");
		Query query = new Query(Criteria.where("title").is(title));
		return mongoTemplate.find(query, Book.class);
	}
	
}
